#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import zipfile
from PIL import Image
from io import BytesIO
from PyQt6.QtWidgets import QMessageBox
from PyQt6.QtGui import QPixmap

class ComicUtils:
    """漫画阅读器工具类，用于处理常见操作和错误情况"""
    
    @staticmethod
    def is_valid_zip(file_path):
        """检查文件是否为有效的ZIP文件"""
        try:
            with zipfile.ZipFile(file_path, 'r') as zip_ref:
                return True
        except zipfile.BadZipFile:
            return False
        except Exception:
            return False
    
    @staticmethod
    def get_image_files_from_zip(file_path):
        """从ZIP文件中获取所有图片文件，并按名称排序"""
        try:
            with zipfile.ZipFile(file_path, 'r') as zip_ref:
                # 获取所有图片文件
                image_files = [f for f in zip_ref.namelist() if f.lower().endswith(('.jpg', '.jpeg', '.png', '.gif', '.webp'))]
                
                # 按名称排序
                image_files.sort()
                
                return image_files
        except Exception as e:
            print(f"获取图片文件出错: {str(e)}")
            return []
    
    @staticmethod
    def extract_cover_image(file_path, max_size=(160, 200)):
        """从ZIP文件中提取第一张图片作为封面"""
        try:
            image_files = ComicUtils.get_image_files_from_zip(file_path)
            
            if not image_files:
                return None, "未找到图片文件"
            
            with zipfile.ZipFile(file_path, 'r') as zip_ref:
                # 获取第一张图片作为封面
                first_image = image_files[0]
                with zip_ref.open(first_image) as img_file:
                    img_data = img_file.read()
                    img = Image.open(BytesIO(img_data))
                    
                    # 调整图片大小
                    img.thumbnail(max_size)
                    
                    # 转换PIL图像为QPixmap
                    # 首先转换为RGB模式（如果不是的话）
                    if img.mode != 'RGB':
                        img = img.convert('RGB')
                    
                    # 将PIL图像转换为字节数据
                    img_bytes = BytesIO()
                    img.save(img_bytes, format='PNG')
                    img_bytes.seek(0)
                    
                    # 从字节数据创建QPixmap
                    qimg = QPixmap()
                    qimg.loadFromData(img_bytes.getvalue())
                    return qimg, image_files
                    
        except zipfile.BadZipFile:
            return None, "无效的ZIP文件"
        except Exception as e:
            return None, f"提取封面出错: {str(e)}"
    
    @staticmethod
    def show_error_message(parent, title, message):
        """显示错误消息对话框"""
        QMessageBox.critical(parent, title, message)
    
    @staticmethod
    def show_warning_message(parent, title, message):
        """显示警告消息对话框"""
        QMessageBox.warning(parent, title, message)
    
    @staticmethod
    def show_info_message(parent, title, message):
        """显示信息消息对话框"""
        QMessageBox.information(parent, title, message)
    
    @staticmethod
    def is_image_file(file_name):
        """检查文件是否为图片文件"""
        return file_name.lower().endswith(('.jpg', '.jpeg', '.png', '.gif', '.webp'))